package com.meteor.security.service;

import com.meteor.framework.common.cache.RedisCache;
import com.meteor.user.entity.SysUser;
import lombok.AllArgsConstructor;
import com.meteor.user.convert.SysUserConvert;
import com.meteor.user.mapper.SysUserMapper;
import com.meteor.user.service.SysUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 账号登录 UserDetailsService
 *
 * @author lynn
 * @date 2024/1/03
 */
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    private final SysUserDetailsService sysUserDetailsService;
    private final SysUserMapper sysUserMapper;
    private final RedisCache redisCache;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        String communityId = (String) redisCache.get("login+"+username+":");

        SysUser userEntity = sysUserMapper.getByUsername(username,null,communityId);
        if (userEntity == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        return sysUserDetailsService.getUserDetails(SysUserConvert.INSTANCE.convertDetail(userEntity));
    }

}
